package nobodyCodesThat;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class CopyThread extends Thread {
	private static Singleton instance = Singleton.getInstance();

	public void run() {
		instance.copyNames = new String[instance.copyHistory];
		Thread.currentThread().setName(Constants.COPY_THREAD);
		instance.time = new Date().getTime();
		long newTime = 0;
		instance.currentSaveGameNumber = 0;
		System.out.println("Starting Thread Time: " + instance.time);
		while (!isInterrupted() && instance.time != 0) {
			checkTQisRunning();
			if (instance.alreadyStartedTQ) {
				newTime = new Date().getTime();
				if (newTime > instance.time + instance.cycleTime) {
					if (instance.currentSaveGameNumber == instance.copyNames.length) {
						instance.currentSaveGameNumber = 0;
					}
					try {
						FileManagement.zipDirectory(instance.inputFolder,
								Constants.HISTORY_FILENAME
										+ instance.currentSaveGameNumber
										+ ".zip");
					} catch (IOException e) {
						e.printStackTrace();
					}
					System.out.println("Creating save copy: "
							+ Constants.HISTORY_FILENAME
							+ instance.currentSaveGameNumber + ".zip");
					instance.time = newTime;
					instance.currentSaveGameNumber++;
				}
			}
			try {
				TimeUnit.SECONDS.sleep(5);
			} catch (InterruptedException e) {
				System.err.println("Timeout was interrupted !");
			}

		}
		if (instance.time == 0) {
			System.out.println("TQ was stopped or crashed");
			return;
		}
		FileManagement.copyNames = instance.copyNames;
	}

	public void stopThread() {
		instance.time = 0;
		Thread.currentThread().interrupt();
	}

	/**
	 * Windows commands are used here, that means it is NOT platform
	 * independent !
	 */
	private void checkTQisRunning() {
		ProcessBuilder builder = new ProcessBuilder(new String[] { "tasklist" });
		builder.directory(new File("c:/"));
		Process p = null;
		try {
			p = builder.start();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		Scanner s = new Scanner(p.getInputStream());
		if (s.findInLine(Constants.TQ_THREADNAME) != null) {
			System.out.println("TQ is running...");
			instance.alreadyStartedTQ = true;
		} else {
			if (instance.alreadyStartedTQ) {
				System.out.println("TQ is now off");
				stopThread();
			} else {
				System.out.println("You can start TQ now");
			}
		}
	}
}